import React,{useState,useEffect} from 'react';  
import {Table ,Modal , Input,message} from 'antd'
import axios from 'axios'
  
export default function User(){
    const [dataSource,setDataSource]=useState([])
    const [messageApi, contextHolder] = message.useMessage();
    const [open,setOpen]=useState(false)
    const [user,setUser]=useState('')
    const [age,setAge]=useState('')
    const [sex,setSex]=useState('')
    const [address,setAddress]=useState('')
    const [phone,setPhone]=useState('')
    const [recordId,setRecordId]=useState('')
    const [filter, setFilter] = useState('');
    useEffect(()=>{
        fetchData();  
    },[filter])
    const fetchData = async () => {  
        try {  
            let res=await axios.get('http://localhost:5000/selectAll',{
                headers:{
                    'token':sessionStorage.getItem('token'),
                    'Content-Type':'application/json;charset=UTF-8'
                }
            })
            var arr=[];
            res.data.data.forEach(item=>{
                if(item.age==null){
                    item.age=""
                }
                if(item.sex==null){
                    item.sex=""
                }
                if(item.idcard==null){
                    item.idcard=""
                }
                if(item.address==null){
                    item.address=""
                }
                if(item.phone==null){
                    item.phone=""
                }
                let obj={
                    id:item.id,
                    username:item.username,
                    age:item.age,
                    sex:item.sex,
                    idcard:item.idcard,
                    address:item.address,
                    phone:item.phone,
                }
                arr.push(obj)
            })
            setDataSource(arr)
        } catch (error) {  
            console.error('Error fetching data:', error);  
        }  
    };
    const hideModal = () => {
        setOpen(false);
    };
    const confirmModal=()=>{
        let obj={
            id:recordId,
            username:user,
            age:age,
            sex:sex,
            address:address,
            phone:phone
        }
        axios({
            method:"post",
            url:'http://localhost:5000/updTest',
            data:obj,
            headers:{
                'token':sessionStorage.getItem('token'),
                'Content-Type':'application/json;charset=UTF-8'
            }
        }).then(res=>{
            if(res.data.code==200){
                messageApi.open({
                    type: 'success',
                    content: '保存成功！',
                });
                setOpen(false);
                setRecordId(0)
                setUser('')
                setAddress('')
                setAge('')
                setSex('')
                setPhone('')
                fetchData();
            }
        })
    }
    const editClick=(record)=>{
        setOpen(true);
        setRecordId(record.id)
        setUser(record.username)
        setAddress(record.address)
        setAge(record.age)
        setSex(record.sex)
        setPhone(record.phone)
    }
    const delClick=(record)=>{
        axios({
            method:"post",
            url:'http://localhost:5000/delUser',
            data:{id:record.id},
            headers:{
                'token':sessionStorage.getItem('token'),
                'Content-Type':'application/json;charset=UTF-8'
            }
        }).then(res=>{
            if(res.data.code==200){
                messageApi.open({
                    type: 'success',
                    content: '删除成功！',
                });
                fetchData();
            }
        })
    }
    const changeUserInput=(e)=>{
        setUser(e.target.value)
    }
    const changeAgeInput=(e)=>{
        setAge(e.target.value)
    }
    const changeSexInput=(e)=>{
        setSex(e.target.value)
    }
    const changeAddressInput=(e)=>{
        setAddress(e.target.value)
    }
    const changePhoneInput=(e)=>{
        setPhone(e.target.value)
    }
 
    const columns = [
        {
            title: '姓名',
            dataIndex: 'username',
            key: 'username',
        },
        {
            title: '年龄',
            dataIndex: 'age',
            key: 'age',
        },
        {
            title: '性别',
            dataIndex: 'sex',
            key: 'sex',
        },
        {
            title: '住址',
            dataIndex: 'address',
            key: 'address',
        },
        {
            title: '电话',
            dataIndex: 'phone',
            key: 'phone',
        },
        {
            title: '操作',
            key: 'action',
            render: (_,record) => (
                <div>
                    <a onClick={()=>editClick(record)}>编辑</a>
                    <a onClick={()=>delClick(record)} style={{marginLeft:20}}>删除</a>
                </div>
            ),
        },
    ]
    return(
        <div>
            {contextHolder}
            <Table dataSource={dataSource} pagination={false} columns={columns} />
            <Modal
                title="编辑"
                open={open}
                onOk={confirmModal}
                onCancel={hideModal}
                okText="确认"
                cancelText="取消"
            >
                  <div>
                      <div style={{marginTop:10}}>
                        <span>姓名：</span>
                        <Input value={user} disabled={true} onChange={changeUserInput} style={{width:300}}/>
                      </div>
                      <div style={{marginTop:10}}>
                        <span>年龄：</span>
                        <Input value={age} onChange={changeAgeInput} style={{width:300}}/>
                      </div>
                      <div style={{marginTop:10}}>
                        <span>性别：</span>
                        <Input value={sex} onChange={changeSexInput} style={{width:300}}/>
                      </div>
                      <div style={{marginTop:10}}>
                        <span>住址：</span>
                        <Input value={address} onChange={changeAddressInput} style={{width:300}}/>
                      </div>
                      <div style={{marginTop:10}}>
                        <span>电话：</span>
                        <Input value={phone} onChange={changePhoneInput} style={{width:300}}/>
                      </div>
                  </div>
            </Modal>
        </div>
    )
}